package zz.app.yzjproject

import android.app.Fragment
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.*

/**
 * 由作者 zzq 于 2017/9/12 22:34 创建
 */
class FuncFragment : Fragment() {
    val funcNameArray = arrayOf("1.设置标准坐姿","2.设置采样频率","3.设置UTC时间","4.查询坐姿与开关机时间","5.查询剩余存储空间","6.设置报警震动次数","7.查询剩余电量",
            "8.设置报警延时时间","9.设置记录时间段")
    lateinit var mListView: ListView
    lateinit var tvSend:TextView
    lateinit var tvReceive:TextView
    lateinit var scrollSend:ScrollView
    lateinit var scrollReceive:ScrollView
    var writeCnt=0
    var readCnt=0

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
        val mContext=context as MainActivity
        val mHandler=mContext.mHandler
        val view = inflater.inflate(R.layout.function_layout, container, false)
        tvSend=view.findViewById(R.id.tvSend)
        tvReceive=view.findViewById(R.id.tvReceive)
        scrollSend=view.findViewById(R.id.scrollSend)
        scrollReceive=view.findViewById(R.id.scrollReceive)
        mListView = view.findViewById(R.id.listView)
        mListView.isEnabled=false
        mListView.adapter = ArrayAdapter<String>(context, R.layout.listview_layout,funcNameArray)
        mListView.onItemClickListener = AdapterView.OnItemClickListener {_,_, position, _ ->
            when(position){
                0->{
                    val v=View.inflate(context,R.layout.standardposture_layout,null)
                    AlertDialog.Builder(context).setTitle("设置标准坐姿：").setPositiveButton("确定",object:DialogInterface.OnClickListener{
                        @RequiresApi(Build.VERSION_CODES.N)
                        override fun onClick(dialog: DialogInterface?, which: Int) {
                            val tvhypsokinesis=v.findViewById<TextView>(R.id.tvhypsokinesis)
                            val tvforerakef=v.findViewById<TextView>(R.id.tvforerakef)
                            val value1=tvhypsokinesis.text?.toString()?.toIntOrNull()
                            val value2=tvforerakef.text?.toString()?.toIntOrNull()
                            if(value1!=null&&value2!=null&&value1>=0&&value1<=90&&value2>=0&&value2<=90) {
                                if (mContext.canComm()) {
                                    mHandler.obtainMessage(HandlerMSG.MSG_SENDCOMMAND, ServerCommand.standardPosture(-value1, value2)).sendToTarget()
                                    sendDebug(ServerCommand.standardPosture(-value1,value2).joinToString(prefix = "[",postfix = "]") { it.toHex() }+"\n->标准坐姿：[${-value1}:${value2}]")

                                }else{
                                    Toast.makeText(mContext, "BLE通信不可用", Toast.LENGTH_SHORT).show()
                                }
                            } else {
                                Toast.makeText(mContext, "参数错误", Toast.LENGTH_SHORT).show()
                            }
                        }

                    }).setNegativeButton("取消",object:DialogInterface.OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {

                        }

                    }).setOnCancelListener (object:DialogInterface.OnCancelListener{
                        override fun onCancel(dialog: DialogInterface?) {

                        }

                    }).setView(v).create().show()

                }
                1->{
                    val v=View.inflate(mContext,R.layout.samplefrequency_layout,null)
                    val rgSampleFrequency=v.findViewById<RadioGroup>(R.id.rgSampleFrequency)
                    rgSampleFrequency.check(R.id.rbOncePerSecond)
                    AlertDialog.Builder(context).setTitle("设置采样频率：").setPositiveButton("确定",object:DialogInterface.OnClickListener{
                        override fun onClick(dialog: DialogInterface?, which: Int) {



                            if (mContext.canComm()) {
                                when(rgSampleFrequency.checkedRadioButtonId){
                                    R.id.rbOncePerSecond->{
                                        mHandler.obtainMessage(HandlerMSG.MSG_SENDCOMMAND, ServerCommand.sampleFrequency(SampleFrequency.OncePerSecond)).sendToTarget()
                                        sendDebug(ServerCommand.sampleFrequency(SampleFrequency.OncePerSecond).joinToString(prefix = "[", postfix = "]") { it.toHex() } + "\n->采样频率："+getString(R.string.strOncePerSecond))
                                    }
                                    R.id.rbTwicePerSecond->{
                                        mHandler.obtainMessage(HandlerMSG.MSG_SENDCOMMAND, ServerCommand.sampleFrequency(SampleFrequency.OncePerTwoSeconds)).sendToTarget()
                                        sendDebug(ServerCommand.sampleFrequency(SampleFrequency.OncePerTwoSeconds).joinToString(prefix = "[", postfix = "]") { it.toHex() } + "\n->采样频率："+getString(R.string.strOncePerTwoSeconds))
                                    }
                                    R.id.rbFourTimesPerSecond->{
                                        mHandler.obtainMessage(HandlerMSG.MSG_SENDCOMMAND, ServerCommand.sampleFrequency(SampleFrequency.OncePerFourSeconds)).sendToTarget()
                                        sendDebug(ServerCommand.sampleFrequency(SampleFrequency.OncePerFourSeconds).joinToString(prefix = "[", postfix = "]") { it.toHex() } + "\n->采样频率："+getString(R.string.strOncePerFourSeconds))
                                    }
                                }


                            } else {
                                Toast.makeText(mContext, "BLE通信不可用", Toast.LENGTH_SHORT).show()
                            }
                        }

                    }).setNegativeButton("取消") { _, _ -> }.setOnCancelListener { }.setView(v).create().show()

                }
                2->{
                    val v=View.inflate(mContext,R.layout.utctime_layout,null)
                    val tvUtcYear=v.findViewById<TextView>(R.id.tvUtcYear)
                    val tvUtcMonth=v.findViewById<TextView>(R.id.tvUtcMonth)
                    val tvUtcDay=v.findViewById<TextView>(R.id.tvUtcDay)
                    val tvUtcHour=v.findViewById<TextView>(R.id.tvUtcHour)
                    val tvUtcMinute=v.findViewById<TextView>(R.id.tvUtcMinute)
                    val tvUtcSecond=v.findViewById<TextView>(R.id.tvUtcSecond)
                    val currentTime=Calendar.getInstance()
                    tvUtcYear.setText(currentTime[Calendar.YEAR].toString())
                    tvUtcMonth.setText((currentTime[Calendar.MONTH]+1).toString())
                    tvUtcDay.setText(currentTime[Calendar.DAY_OF_MONTH].toString())
                    tvUtcHour.setText(currentTime[Calendar.HOUR_OF_DAY].toString())
                    tvUtcMinute.setText(currentTime[Calendar.MINUTE].toString())
                    tvUtcSecond.setText(currentTime[Calendar.SECOND].toString())
                    AlertDialog.Builder(context).setTitle("设置UTC时间：").setPositiveButton("确定") { _, _ ->
                        if (mContext.canComm()) {
                            val year=tvUtcYear.text.toString().toIntOrNull()
                            val month=tvUtcMonth.text.toString().toIntOrNull()
                            val day=tvUtcDay.text.toString().toIntOrNull()
                            val hour=tvUtcHour.text.toString().toIntOrNull()
                            val minute=tvUtcMinute.text.toString().toIntOrNull()
                            val second=tvUtcSecond.text.toString().toIntOrNull()
                            if(isCorrectDateTime(year,month,day,hour,minute,second)){
                                val temp=ServerCommand.utcTime(year!!,month!!,day!!,hour!!,minute!!,second!!)
                                mHandler.obtainMessage(HandlerMSG.MSG_SENDCOMMAND,temp).sendToTarget()
                                sendDebug(temp.joinToString(prefix = "[", postfix = "]") { it.toHex() }
                                        + "\n->设置时间：${year}年${month}月${day}日 ${hour}时${minute}分${second}秒\n->Long:${Utils.convertDateTimeToUTCTimeSecond(
                                        year,month,day,hour,minute,second
                                )}")

                            } else{

                            }

                        } else {
                            Toast.makeText(mContext, "BLE通信不可用", Toast.LENGTH_SHORT).show()
                        }
                    }.setNegativeButton("取消") { _, _ -> }.setOnCancelListener { }.setView(v).create().show()

                }
            }
        }

        return view


    }
    @RequiresApi(Build.VERSION_CODES.M)
    fun sendDebug(debug:String){
        val mContext=context as MainActivity?
        var str=tvSend.text.toString()
        str+=(++writeCnt).toString()+":"
        str+=debug+"\n\n"
        tvSend.text=str
        mContext?.mHandler?.post {
            val offset=if(tvSend.measuredHeight-scrollSend.height<0) 0 else tvSend.measuredHeight-scrollSend.height
            scrollSend.scrollTo(0, offset); }

    }
    @RequiresApi(Build.VERSION_CODES.M)
    fun receiveDebug(debug:String){
        val mContext=context as MainActivity?
        var str=tvReceive.text.toString()
        str+=(++readCnt).toString()+":"
        str+=debug+"\n\n"
        tvReceive.text=str

        mContext?.mHandler?.post {
            val offset=if(tvReceive.measuredHeight-scrollReceive.height<0) 0 else tvReceive.measuredHeight-scrollReceive.height
            scrollReceive.scrollTo(0, offset); }
    }
    fun isCorrectDateTime(year:Int?,month:Int?,day:Int?,hour:Int?,minute:Int?,second:Int?):Boolean{
        if(year==null||month==null||day==null||hour==null||minute==null||second==null)
            return false
        val isLeapYear=year.isLeapYear()
        if(year<1900||year>2100)return false
        if(month<1||month>=12)return false
        if(day<1||day>Utils.DayOfMonth(month,isLeapYear))return false
        if(hour<0||hour>23)return false
        if(minute<0||minute>59)return false
        if(second<0||second>59)return false
        return true


    }
}

fun Byte.toHex(): String {
    var str="0X"
    val chararray= CharArray(16,{
        when{
            it<10 -> (it+48).toChar()
            it==10->'A'
            it==11->'B'
            it==12->'C'
            it==13->'D'
            it==14->'E'
            it==15->'F'
            else->throw IllegalArgumentException()
        }
    })
    var i=this.toInt()
    if(i<0)i+=256
    str+=chararray[i/16]
    str+=chararray[i%16]
    return str
}
